package flst.ipiweb.presentation.article;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;

import flst.ipiweb.transverse.Admin;


public class UploadImageArticleAction extends Action{

	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// Modifications pour la gestion de session
		HttpSession sess = request.getSession(true);
		Admin adm = (Admin)sess.getAttribute("User");
		if (adm!=null){
			  UploadImageArticleForm myForm = (UploadImageArticleForm)form;
			  FormFile myFile = myForm.getFichier();
			  String contentType = myFile.getContentType();
			  String fileName  = myFile.getFileName();
			  int fileSize = myFile.getFileSize();
			  byte[] fileData  = myFile.getFileData();
			  String filePath = getServlet().getServletContext().getRealPath("/") +"upload";
			    /* Sauvegarde du fichier dans le serveur */
			  if(!fileName.equals("")){  
			        System.out.println("Serveur path:" +filePath);
			        //creer le fichier
			        File fileToCreate = new File(filePath, fileName);
			        //si le fichier n'existe pas, il faut le sauvegarder                     
			        if(!fileToCreate.exists()){
			          FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
			          fileOutStream.write(myFile.getFileData());
			          fileOutStream.flush();
			          fileOutStream.close();
			        }
			       
			       
			    }
			return null;
		}
		else{
			return mapping.findForward("ArticleKo");
		}
	}
}
